import React from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  Checkbox,
  InputNumber,
  Space,
  Tabs,
  DatePicker,
  Upload,
  Select,
  Alert,
  Row,
  Col,
} from 'antd';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import moment from 'moment';
import Categories from '@/pages/admin/categories';

const currControl = 'Edu_Distributor';
const { confirm } = Modal;
const { TabPane } = Tabs;

class CourseEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      fileList: [],
      banks: [],
      comRate: 0.01,
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
    }
    this.fetchCategory();
  }
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'banks' },
      })
      .then(() => {
        let items = this.props.Category.response.result;
        let banks: any = [];
        items.forEach((element: any) => {
          var obj = {
            text: element.node.categoryName,
            value: element.node.categoryIndex,
          };
          banks.push(obj);
        });
        this.setState({ banks });
      });
  };
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        if (result.businesslicense) {
          var fileList: any = [];
          var pics = result.businesslicense.split(',');
          pics.forEach((element: any) => {
            var obj = {
              uid: element,
              name: element,
              response: {
                result: element,
              },
              status: 'done',
              url: UploadUtil.imgServ + element,
            };
            fileList.push(obj);
          });
          this.setState({ fileList });
        }
        if (result.startDate) result.startDate = moment(result.startDate);
        if (result.endDate) result.endDate = moment(result.endDate);
        this.setState({ datas: result });
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    if (this.state.fileList) {
      var pics: string[] = [];
      this.state.fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.businesslicense = pics.toString();
    } else {
      values.model.businesslicense = this.state.datas.businesslicense;
    }
    console.log(values);

    values.model.startDate = values.model.startDate?.format('YYYY-MM-DD');
    values.model.endDate = values.model.endDate?.format('YYYY-MM-DD');
    console.log(values);

    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() { },
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'done' && info.file.response) {
      this.setState({
        imageUrl: info.file.response.result,
      });
    }
  };
  handleUploadList = (info: any) => {
    this.setState({ fileList: info.fileList });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  handleGrdChg = (value: any) => {
    let obj = this.formRef.current.getFieldsValue();
    obj.model.commissionRate = value / 100;
    this.formRef.current.setFieldsValue({ model: obj.model });
  };
  render() {
    const { datas, loading, fileList, banks } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传资质</div>
      </div>
    );
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本" key="1">
              <Form.Item label="id" name={['model', 'id']} hidden>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'disbNO']} label="商户编号" hidden>
                <Input disabled />
              </Form.Item>


              <Row gutter={4}>
                <Col span={12}><Form.Item
                  name={['model', 'disbName']}
                  label="商户名称"
                  rules={[{ required: true, message: '请输入商户名称' }]}
                >
                  <Input />
                </Form.Item></Col>
                <Col span={12}> <Form.Item
                  name={['model', 'superiorNumber']}
                  label="上级编号"
                >
                  <Input />
                </Form.Item></Col>
                <Col span={12}>
                  <Form.Item name={['model', 'distype']} label="注册类型" rules={[{ required: true, message: '请选择注册类型' }]}>
                    <Select>
                      <Select.Option value={'个人'}>个人</Select.Option>
                      <Select.Option value={'医生'}>医生</Select.Option>
                      <Select.Option value={'渠道商'}>渠道商</Select.Option>
                      <Select.Option value={'顾问医生'}>顾问医生</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['model', 'channel']} label="注册渠道">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['model', 'hospital']} label="所属医院">
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['model', 'department']} label="所属科室">
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>

                  <Form.Item
                    name={['model', 'mobile']}
                    label="手机号码"
                    rules={[{ required: true, message: '请输入手机号码' }]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'password']}
                    label="初始密码"
                    hidden={datas.id}
                    rules={[{ required: true, message: '请输入初始密码' }]}
                  >
                    <Input.Password />
                  </Form.Item>
                </Input.Group>
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item
                    name={['model', 'startDate']}
                    label="开始日期"
                    rules={[{ required: true, message: '请输入开始日期' }]}
                  >
                    <DatePicker />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'endDate']}
                    label="截至日期"
                    rules={[{ required: true, message: '请输入截至日期' }]}
                  >
                    <DatePicker />
                  </Form.Item>
                </Input.Group>
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item
                    name={['model', 'grade']}
                    label="分销等级"
                  >
                    <Select style={{ width: 150 }} onChange={this.handleGrdChg}>
                      <Select.Option value={1}>基本分销</Select.Option>
                      <Select.Option value={2}>中级分销</Select.Option>
                      <Select.Option value={3}>高级分销</Select.Option>
                    </Select>
                  </Form.Item>
                  <Form.Item
                    name={['model', 'commissionRate']}
                    label="个人佣金比率"
                    rules={[{ required: true, message: '请填写个人佣金比率' }]}
                  >
                    <InputNumber min={0} step={0.01} style={{ width: "150px" }} />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'commissionRate2']}
                    label="来自下级佣金比率"
                  >
                    <InputNumber min={0} step={0.01} style={{ width: "200px" }} />
                  </Form.Item>
                </Input.Group>
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'enabled']} valuePropName="checked">
                    <Checkbox disabled>生效</Checkbox>
                  </Form.Item>
                  <Form.Item name={['model', 'isApprve']} valuePropName="checked">
                    <Checkbox>审核</Checkbox>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
            </TabPane>
            <TabPane tab="联系方式" key="2">
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'contactor']} label="联系人">
                    <Input />
                  </Form.Item>
                  <Form.Item name={['model', 'phone']} label="联系电话">
                    <Input />
                  </Form.Item>
                  <Form.Item name={['model', 'fax']} label="传真号码">
                    <Input />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'email']} label="电子邮箱">
                    <Input />
                  </Form.Item>
                  <Form.Item name={['model', 'wx']} label="微信号">
                    <Input />
                  </Form.Item>
                  <Form.Item name={['model', 'qq']} label="QQ">
                    <Input />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item name={['model', 'address']} label="联系地址">
                <Input />
              </Form.Item>
            </TabPane>
            <TabPane tab="资质认证" key="3">
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'legalPerson']} label="法人姓名">
                    <Input />
                  </Form.Item>
                  <Form.Item name={['model', 'entIdNum']} label="企业证件号">
                    <Input style={{ width: 260 }} />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item name={['model', 'bank']} label="开户行">
                    <Select style={{ width: 150 }}>
                      {banks.map((item: any) => (
                        <Select.Option value={item.value} key={item.value}>
                          {item.text}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                  <Form.Item name={['model', 'bankBranch']} label="分行名称">
                    <Input />
                  </Form.Item>
                  <Form.Item label="↓">
                    <Button onClick={() => this.openModal(null, 'banks')} icon={<PlusOutlined />}>
                      添加银行
                    </Button>
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item name={['model', 'bankAccount']} label="银行账号">
                <Input />
              </Form.Item>
              <Form.Item label="资质证书">
                <Upload
                  action={UploadUtil.actionURL}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: currControl,
                    objectField: 'Businesslicense',
                  }}
                  name="files"
                  listType="picture-card"
                  fileList={fileList}
                  multiple={true}
                  onChange={this.handleUploadList}
                >
                  {fileList.length >= 12 ? null : uploadButton}
                </Upload>
              </Form.Item>
              <Form.Item>
                <Alert
                  message="请上传企业营业执照、法人身份证正反照片予以我们资质审核。"
                  type="warning"
                  showIcon
                  closable
                />
              </Form.Item>
            </TabPane>

            <TabPane tab="佣金" key="4">
              <Row>
                <Col span="18">
                  <Form.Item name={['model', 'commissionAmt']} label="总佣金" >
                    <Input disabled />
                  </Form.Item></Col>
                <Col span="18">
                  <Form.Item name={['model', 'notCashOutAmt']} label="可体现" >
                    <Input disabled />
                  </Form.Item></Col>
                <Col span="18">
                  <Form.Item name={['model', 'cashOutAmt']} label="已提现" >
                    <Input disabled />
                  </Form.Item></Col>
              </Row>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>
                保存
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Modal
          title="银行分类"
          visible={this.state.visible}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible: false })}
          width={700}
          footer={false}
        >
          <Categories layout={this.state.layout} size="small" fetchCategory={this.fetchCategory} />
        </Modal>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(CourseEdit);
